#include "stdafx.h"
#include "Cutscene.h"

Cutscene::Cutscene() : finished(false), sprites(0), textures(0)
{}

void Cutscene::Play(std::vector<const char*>& images, std::vector<bool>& directions, sf::RenderWindow& window)
{
	finished = false;
	iterator = 0;
	
	if (sprites)
		delete[] sprites;
	if (textures)
		delete[] textures;

	sprites = new sf::Sprite[images.size()];
	textures = new sf::Texture[images.size()];

	for (int i = 0; i < images.size(); ++i)
	{
		textures[i].loadFromFile(images[i]);
		sprites[i].setTexture(textures[i], true);
	}

	appearingScene = &sprites[0];
	appearingScene->setColor(sf::Color(255,255,255,0));
	disappearingScene = 0;
	float accumulator = 0.0f;
	float timer = 0.0f;
	sf::Clock frameClock;
	sf::View view;

	while(window.isOpen() && !finished)
	{
		sf::Event event;

		while(window.pollEvent(event))
		{
			if(event.type == sf::Event::Closed)
				window.close();
			else if ( event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape )
			{
				window.close();
			}   
		}

		sf::Vector2u screenSize = window.getSize();
		if(screenSize.x == 0) screenSize.x = 0;
		view.setSize(sf::Vector2f(600.0f *  screenSize.x / screenSize.y, 600.0f));
		view.setCenter(view.getSize() * 0.5f);

		accumulator += frameClock.getElapsedTime().asSeconds();
		frameClock.restart();

		if(accumulator > 6.0f / 60.0f) accumulator = 6.0f / 60.0f;

		while(accumulator >= 1.0f / 60.0f)
		{
			accumulator -= 1.0f / 60.0f;
			
			if (!appearingScene)
			{
				if (timer >= 2.0f)
					finished = true;
				else
					disappearingScene->setColor(sf::Color(255,255,255,255.f * (1.f - timer * 0.5f)));
				timer += DELTA;
			}
			else
			{
				if (timer >= 5.0f)
				{
					disappearingScene = appearingScene;
					if (++iterator == images.size())
						appearingScene = 0;
					else
					{
						appearingScene = &sprites[iterator];
						appearingScene->setColor(sf::Color(255,255,255,0));
					}
					timer = 0.f;
				}
				else
				{
					float appear = (timer * 0.4f > 1.f) ? 1.f : timer * 0.4f;
					appearingScene->setColor(sf::Color(255,255,255,255.f * appear));
					if (directions[iterator])
						appearingScene->setPosition((view.getSize().x - appearingScene->getLocalBounds().width) * timer * 0.2f, 0.f);
					else
						appearingScene->setPosition((view.getSize().x - appearingScene->getLocalBounds().width) * (1.f - timer * 0.2f), 0.f);
					timer += DELTA;
				}
			}
		}

		window.setView(view);
		window.clear(sf::Color(0, 0, 0));


		if (disappearingScene)
			window.draw(*disappearingScene);
		if (appearingScene)
			window.draw(*appearingScene);

		window.display();
	}
}